#!/usr/bin/env python
# -*- coding:utf-8 -*-
import socket, sys, os
from socketserver import BaseServer
from http.server import HTTPServer,SimpleHTTPRequestHandler
from OpenSSL import SSL
import json
from urllib.parse import urlparse

PEM_PATH = os.path.dirname(os.path.realpath(__file__)) + os.sep + "server.pem"

class SecureHTTPServer(HTTPServer):
    def __init__(self, server_address, HandlerClass, fpem):
        BaseServer.__init__(self, server_address, HandlerClass)
        ctx = SSL.Context(SSL.SSLv23_METHOD)
        ctx.use_privatekey_file(fpem)
        ctx.use_certificate_file(fpem)
        self.socket = SSL.Connection(ctx, socket.socket(self.address_family,
                                                        self.socket_type))
        self.server_bind()
        self.server_activate()

    def shutdown_request(self,request):
        request.shutdown()

class SecureHTTPRequestHandler(SimpleHTTPRequestHandler):
    def setup(self):
        self.connection = self.request
        self.rfile = socket.SocketIO(self.request, "rb")
        self.wfile = socket.SocketIO(self.request, "wb")
        self.response = {}

    def set_json_header(self):
        self.send_response(200)
        self.send_header('Content-type', 'application/json')
        self.send_header('Access-Control-Allow-Origin','*')#允许跨域
        self.end_headers()

    def send_json_success(self,data:str):
        self.response['code'] = 0
        self.response['msg'] = ''
        self.response['data'] = data
        self.set_json_header()
        resp = self.get_byte_resp(json.dumps(self.response))
        self.wfile.write(json.dumps(self.response))
    
    def get_byte_resp(self,resp:str):
        return resp.encode()
    def do_GET(self) -> None:
        querypath = urlparse(self.path)
        filepath, query = querypath.path, querypath.query
        print("请求地址: " + filepath)
        self.send_json_success("服务器响应: HTTPS_GET请求成功接收!")
        return super().do_GET()

    def do_POST(self):
        print("请求地址: " + self.path)
        datas = self.rfile.read(int(self.headers['content-length']))
        print("请求参数: " + str(datas,"utf-8"))
        self.send_json_success("服务器响应: HTTPS_POST请求成功接收!")

def runServer(HandlerClass = SecureHTTPRequestHandler,
         ServerClass = SecureHTTPServer, port=5566):
    server_address = ('', port)
    httpd = ServerClass(server_address, HandlerClass, PEM_PATH)
    sa = httpd.socket.getsockname()
    print("HTTPS服务启动!")
    print("监听端口: " + str(port) +"...")
    httpd.serve_forever()


if __name__ == '__main__':
    runServer()